﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using iHouse.Model.Data;
using iHouse.Model.Repository.Interface;
using Microsoft.Practices.Unity;
using iHouse.Web.Infrastructure;
using iHouse.Common.Const;
using System.Web.Routing;

namespace iHouse.Web.Controllers
{
    public abstract class BaseController : Controller
    {
        protected virtual int DefaultPageSize
        {
            get
            {
                return 10;
            }
        }

        [Dependency]
        public ICategoryRepository CategoryRespository { get; set; }

        protected IEnumerable<Category> Categories
        {
            get
            {
                return CategoryRespository.GetCategoriesByType((int)ControllerType);
            }
        }

        protected virtual string HomeView
        {
            get
            {
                return string.Empty;
            }
        }

        protected abstract CategoryType ControllerType
        {
            get;
        }

        public virtual ActionResult InitCategoryList()
        {
            return View();
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.ActionParameters.ContainsKey("pageSize"))
            {
                filterContext.ActionParameters["pageSize"] = DefaultPageSize;
            }

            if (filterContext.ActionParameters.ContainsKey("page"))
            {
                object page = filterContext.ActionParameters["page"];
                if (page == null)
                    filterContext.ActionParameters["page"] = 1;

                ViewBag.CurrentPage = page;
            }

            if (filterContext.ActionParameters.ContainsKey("category"))
            {
                ViewBag.SelectedCategory = filterContext.ActionParameters["category"];
            }

            List<CategoryFormView> list = new List<CategoryFormView>();

            foreach (var c in this.CategoryRespository.GetAllCategories())
            {
                CategoryFormView view = new CategoryFormView();
                view.Action = this.HomeView;
                view.TypeName = ((CategoryType)c.Key).ToString();
                view.Items = c;

                list.Add(view);
            }

            ViewBag.Categories = list;
        }
    }
}